import React, { useState } from "react";
import { View, StyleSheet, Dimensions, Text, ImageBackground, TouchableOpacity, Clipboard, Image } from "react-native";
import wif from 'wif'
import Toast from 'react-native-simple-toast'
import "@ethersproject/shims";
import { ethers } from 'ethers';
import LockScreenEnter from '@/components/LockScreenEnter'
import Loading from "@/components/LoadingModal";
import { getValue } from '@/utils/deviceStorage'
import CommonContext from '@/utils/createContext'
import IconNavBar from "@/components/IconNavBar";
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import { Shadow } from "react-native-shadow-2";
import { AESdecrypt } from "@/utils/util";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const ShowPrivateKey = (props) => {

    const [privateKeyList, setPrivateKeyList] = useState([])
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [selectedItem, setSelectedItem] = useState('')
    const [modalVisible, setModalVisible] = useState(true)

    const handleClose = () => {
        setModalVisible(false)
        setTimeout(() => {
            let pwd = getValue('lockPwd')
            let encryptStr = getValue('mnemonicStr')
            let decryptStr = AESdecrypt(pwd.substring(0, 16), pwd.substring(16), encryptStr)
            if (decryptStr) {
                setLoadingVisible(true)
                setTimeout(() => {
                    getPrivateData(str)
                }, 500);
            }
        }, 500);
    }

    const getPrivateData = (mnemonicStr) => {
        let selectedWallet = getValue('selectedWallet')
        const Wallet = ethers.Wallet.fromMnemonic(mnemonicStr, selectedWallet.wallet_name)
        const privateKey = Wallet.privateKey
        var buffer = Buffer.from(privateKey, 'hex')
        const privateKeyWif = wif.encode(128, buffer, false)
        const privateKeyWifCompress = wif.encode(128, buffer, true)
        let arr = [{
            format: 'Hex',
            value: privateKey
        }, {
            format: 'Compress(WIF)',
            value: privateKeyWifCompress
        }, {
            format: 'No Compress(WIF)',
            value: privateKeyWif
        }]
        setPrivateKeyList(arr)
        setSelectedItem(arr[0])
        setLoadingVisible(false)
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressItem = (item) => {
        Clipboard.setString(item.value)
        setSelectedItem(item)
        Toast.showWithGravity(
            'privateKey copied to clipboard',
            Toast.SHORT,
            Toast.CENTER)
    }

    return (
        <View style={styles.container}>
            <IconNavBar {...props} handlePressLeft={handlePressLeft}
                {...sectokenCommonCenterProps}
                {...{ title: 'Show PrivateKey', backgroundColor: '#F5F6FA' }} />
            <View style={styles.bodyContent}>
                {privateKeyList ? privateKeyList.map((item, index) => {
                    const isSelected = selectedItem.value === item.value
                    return (
                        <TouchableOpacity key={index} style={{ marginTop: 10 * ratio }} onPress={() => { handlePressItem(item) }}>
                            <Shadow offset={[3, 6]}
                                distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent' radius={10}>
                                <View style={styles.itemContent}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10 * ratio }}>
                                        <View style={{ flexDirection: 'row' }}>
                                            <Text style={{ ...styles.title2, marginLeft: 14 * ratio }}>Private key format</Text>
                                            <View style={styles.formatContent}>
                                                <Text style={{ ...styles.title2 }}>{item.format}</Text>
                                            </View>
                                        </View>
                                        {isSelected && <ImageBackground style={{ width: 40 * ratio, height: 42 * ratio, marginTop: -10 * ratio }}
                                            source={require('@/assets/imgs/checked.png')} />}
                                    </View>
                                    <Text style={{ ...styles.title2, marginTop: isSelected ? 0 : 12 * ratio, marginLeft: 14 * ratio }}>Prohibit screenshots</Text>
                                    <Text style={{ ...styles.title3, marginTop: 6 * ratio, marginLeft: 14 * ratio }}>
                                        Do not save the private key in networked devices, any network disks and chat tools
                                    </Text>
                                    <Text style={{ ...styles.title2, marginTop: 6 * ratio, marginLeft: 14 * ratio }}>No sharing</Text>
                                    <Text style={{ ...styles.title3, marginTop: 6 * ratio, marginLeft: 14 * ratio }}>
                                        It is forbidden to disclose the private key to anyone, otherwise the assets will be lost
                                    </Text>
                                    <View style={{ alignItems: 'center' }}>
                                        <View style={styles.keyContent}>
                                            <Text style={{ ...styles.title3, width: 217 * ratio }}>
                                                {item.value}
                                            </Text>
                                        </View>
                                    </View>
                                </View>
                            </Shadow>
                        </TouchableOpacity>
                    )
                }) : <></>}
                <View style={{ flex: 1, justifyContent: 'flex-end', marginBottom: 40 * ratio }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Image source={require('@/assets/imgs/logo.png')} style={{ width: 20 * ratio, height: 18 * ratio }} />
                        <Text style={styles.title1}>Sectoken</Text>
                    </View>
                </View>
            </View>
            {modalVisible && <CommonContext.Provider value={{ modalVisible, setModalVisible, handleClose }}>
                <LockScreenEnter {...props} />
            </CommonContext.Provider>}
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F6FA'
    },
    bodyContent: {
        flex: 1,
        marginTop: 28 * ratio,
        alignItems: 'center'
    },
    itemContent: {
        width: 330 * ratio,
        height: 195 * ratio,
        backgroundColor: '#FFFFFF',
        borderRadius: 10
    },
    formatContent: {
        width: 130 * ratio,
        height: 20 * ratio,
        backgroundColor: '#F5F6FA',
        borderRadius: 8,
        alignItems: 'center',
        justifyContent: 'center',
        marginLeft: 14 * ratio
    },
    keyContent: {
        width: 293 * ratio,
        height: 37 * ratio,
        backgroundColor: '#F5F6FA',
        borderRadius: 8,
        alignItems: 'center',
        marginTop: 6 * ratio,
        justifyContent: 'center'
    },
    title1: {
        fontSize: 13,
        fontFamily: 'Microsoft YaHei',
        fontWeight: 'bold',
        color: '#DADAE3',
        lineHeight: 18
    },
    title2: {
        fontSize: 12,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#000000',
        lineHeight: 16
    },
    title3: {
        fontSize: 10,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#707070',
        lineHeight: 13
    }
})
export default ShowPrivateKey